package com.tinem.platform.service.network.client.impl;

import com.tinem.platform.module.starter.jpa.entity.network.IpInfo;
import com.tinem.platform.service.network.client.IpInfoClient;
import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbMakerConfigException;
import org.lionsoul.ip2region.DbSearcher;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @author fzh
 * @version v1
 * @program: platform
 * @className Ip2region
 * @description 通过Ip2region获取ip信息
 * @site
 * @company
 * @create 2021-10-27 14:39
 */
@Slf4j
@Service
@Configuration
public class Ip2regionIpInfoClient  implements IpInfoClient {


    @Resource
    DbSearcher dbSearcher;

    @Override
    public IpInfo getLocationByIp(String ip) {

        DataBlock dataBlock = null;
        try {
            dataBlock = dbSearcher.binarySearch(ip);
        } catch (IOException e) {
            log.error("search ip:({}) error.",ip,e);
            return null;
        }
        String[] region = dataBlock.getRegion().split("\\|");
        IpInfo ipInfo = new IpInfo();
        ipInfo.setIp(ip);
        ipInfo.setCountry(region[0]);
        ipInfo.setRegion(region[1]);
        ipInfo.setProvince(region[2]);
        ipInfo.setCity(region[3]);
        ipInfo.setIsp(region[4]);
        return ipInfo;
    }

    @Bean
    public DbSearcher dbSearcher(@Value("${ip.db-file}") String dbFile) throws DbMakerConfigException, FileNotFoundException {
        DbConfig config = new DbConfig();
        return new DbSearcher(config, dbFile);
    }
}
